package com.xdxc.utils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.util.Arrays;

public class IpAddressUtils {

    public static boolean isInRange(String ip, String cidr) {
        try {
            String[] parts = cidr.split("/");
            InetAddress ipAddr = InetAddress.getByName(ip);
            InetAddress networkAddr = InetAddress.getByName(parts[0]);

            byte[] ipBytes = ipAddr.getAddress();
            byte[] networkBytes = networkAddr.getAddress();

            if (ipBytes.length != networkBytes.length) {
                return false;
            }

            int prefix = parts.length > 1 ? Integer.parseInt(parts[1]) : 32;
            int mask = 0xffffffff << (32 - prefix);

            ByteBuffer ipBuffer = ByteBuffer.wrap(ipBytes);
            ByteBuffer networkBuffer = ByteBuffer.wrap(networkBytes);

            return (ipBuffer.getInt() & mask) == (networkBuffer.getInt() & mask);
        } catch (Exception e) {
            return false;
        }
    }

    public static String getClientIp(HttpServletRequest request) {
        String[] headers = {
                "X-Forwarded-For",
                "Proxy-Client-IP",
                "WL-Proxy-Client-IP",
                "HTTP_CLIENT_IP",
                "HTTP_X_FORWARDED_FOR"
        };

        String ip = Arrays.stream(headers)
                .map(request::getHeader)
                .filter(header -> header != null && !header.isEmpty() && !"unknown".equalsIgnoreCase(header))
                .findFirst()
                .orElse(request.getRemoteAddr());

        return ip.split(",")[0].trim();
    }
}